<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use DB;
use Storage;
use Illuminate\Support\Facades\Redis;
use Exception;

/**
 * Class ShopInfo
 * @package App
 */
class ShopInfo extends Model
{
    public $timestamps = false;
    protected $table = 's_shanghu';

    const DEL_OFF = 0;
    const DEL_ON = 1;

    const COVER_ON = 1;
    const COVER_OFF = 0;

    const HOT_ON = 1;
    const HOT_NO = 0;

    static $HotDisplay = [
        self::HOT_NO => '不推荐',
        self::HOT_ON => '推荐',
    ];

    //审核状态
    const STATUS_WAITING = 1;
    const STATUS_YES = 2;
    const STATUS_NEW = 3;
    const STATUS_REFUSE = 4;

    static $StatusDisplay = [
        self::STATUS_WAITING => '待审核',
        self::STATUS_YES => '审核通过',
        self::STATUS_NEW => '新信息审核中',
        self::STATUS_REFUSE => '审核失败',
    ];


    //聊天权限
    const CONSULT_TYPE_IMG = 1;
    const CONSULT_TYPE_VIOCE = 2;
    const CONSULT_TYPE_VIDEO = 3;

    static $DisplayConsultType = [
        self::CONSULT_TYPE_IMG => '图文',
        self::CONSULT_TYPE_VIOCE => '语音',
        self::CONSULT_TYPE_VIDEO => '视频',
    ];

    //提现方式
    const WITHDRAW_TYPE_ALIPAY = 1;
    const WITHDRAW_TYPE_WECHAT = 2;

    static $WithdrawTypeDisplay = [
        self::WITHDRAW_TYPE_ALIPAY => '支付宝',
        self::WITHDRAW_TYPE_WECHAT => '微信',
    ];


    const MESSAGE_STATUS_YES = '';
    const MESSAGE_STATUS_REFUSE = '';

    #######关联关系
    //会员级别
    function vip()
    {
        return $this->belongsTo(Vip::class, 'vip', 'id');
    }


    ######关联关系end

    /**
     * 添加商铺信息
     * @param $request
     * @return array
     */
    static function ShopPublish($request)
    {
        DB::beginTransaction();


        if ($request->has('pic_s')) {
            $pic_s = Storage::url(Postings::OssUpdate($request->pic_s));
        } else {
            $pic_s = '';
        }
        if ($request->has('pic1')) {
            $pic1 = Storage::url(Postings::OssUpdate($request->pic1));
        } else {
            $pic1 = '';
        }
        if ($request->has('pic2')) {
            $pic2 = Storage::url(Postings::OssUpdate($request->pic2));
        } else {
            $pic2 = '';
        }
        if ($request->has('pic3')) {
            $pic3 = Storage::url(Postings::OssUpdate($request->pic3));
        } else {
            $pic3 = '';
        }
        $hot = $request->has('is_hot') ? self::HOT_ON : self::HOT_NO;
        $insert = DB::table('s_shanghu')->insertGetId([
            'uuid' => Curl::CreateUuid(),
            'introduce' => strip_tags($request->contents),
            'store_name' => $request->shopname,
            'store_type' => $request->store_type,
            'store_title' => $request->store_title,
            'lng' => $request->lng,
            'lat' => $request->lat,
            'url' => $request->url,
            'is_hot' => $hot,
            'address1' => $request->address1,
            'address2' => $request->address2,
            'address3' => $request->address3,
            'business_time1' => $request->business_time1,
            'business_time2' => $request->business_time2,
            'city' => $request->city,
            'pin_pic' => ShanghuType::where('store_type', $request->store_type)->value('pin_pic'),
        ]);

        if (!$insert) {
            DB::rollBack();

            return ['status' => 2, 'message' => '添加失败'];
        }
        //添加phone
        $phones = explode(' ',$request->phone);
        //添加
        $phones_insert = [];
        foreach ($phones as $phone) {
            $phones_insert[] = [
                'shanghu_id' => $insert,
                'phone_num' => $phone
            ];
        }
        $phone_update = DB::table('s_shanghu_phone')->insert($phones_insert);
        if (!$phone_update) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }
        //添加pic
        $pic = [
            [
                'shanghu_id' => $insert,
                'pic' => $pic_s,
                'cover' => self::COVER_ON
            ],
            [
                'shanghu_id' => $insert,
                'pic' => $pic1,
                'cover' => self::COVER_OFF
            ],
            [
                'shanghu_id' => $insert,
                'pic' => $pic2,
                'cover' => self::COVER_OFF
            ],
            [
                'shanghu_id' => $insert,
                'pic' => $pic3,
                'cover' => self::COVER_OFF
            ]
        ];
        $pid_insert = DB::table('s_shanghu_pic')->insert($pic);
        if (!$pid_insert) {
            DB::rollBack();

            return ['status' => 2, 'message' => '添加失败'];
        }

        //添加经纬度到redis
        Redis::geoadd('location', $request->lng, $request->lat, $insert);
        DB::commit();

        return ['status' => 1, 'message' => '添加成功'];
    }


    /**
     * 修改店铺信息
     * @param $request
     * @param $shopInfo
     * @return array
     * @throws \Exception
     */
    static function ShopModify($request, $shopInfo)
    {
        $hot = $request->has('is_hot') ? self::HOT_ON : self::HOT_NO;
        $insert = DB::table('s_shanghu')->where('id', $shopInfo->id)->update([
            'introduce' => strip_tags($request->contents),
            'store_name' => $request->shopname,
            'store_type' => $request->store_type,
            'store_title' => $request->store_title,
            'lng' => $request->lng,
            'lat' => $request->lat,
            'url' => $request->url,
            'is_hot' => $hot,
            'address1' => $request->address1,
            'address2' => $request->address2,
            'address3' => $request->address3,
            'business_time1' => $request->business_time1,
            'business_time2' => $request->business_time2,
            'city' => $request->city,
            'pin_pic' => ShanghuType::where('store_type', $request->store_type)->value('pin_pic'),
        ]);
        //添加phone
        $phones = explode(' ',$request->phone);
        //删掉以前的电话
        DB::table('s_shanghu_phone')->where('shanghu_id', $shopInfo->id)->delete();
//        if (!DB::table('s_shanghu_phone')->where('shanghu_id', $shopInfo->id)->delete()) {
//            DB::rollBack();
//
//            return ['status' => 2, 'message' => '失败'];
//        }
        //添加
        $phones_insert = [];
        foreach ($phones as $phone) {
            $phones_insert[] = [
                'shanghu_id' => $shopInfo->id,
                'phone_num' => $phone
            ];
        }
        $phone_update = DB::table('s_shanghu_phone')->insert($phones_insert);
        if (!$phone_update) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }
        //添加pic
        //获取name
        $pics = DB::table('s_shanghu_pic')->where('shanghu_id', $shopInfo->id)->pluck('id')->toArray();
        foreach ($pics as $pic) {
            $name = 'pic' . $pic;
            if ($request->has($name)) {
                $path = Storage::url(Postings::OssUpdate($request->$name));
                DB::table('s_shanghu_pic')->where('id', $pic)->update(['pic' => $path]);
            }
        }

        //添加经纬度到redis
        Redis::geoadd('location', $request->lng, $request->lat, $shopInfo->id);
        DB::commit();

        return ['status' => 1, 'message' => '修改成功'];
    }


    /**
     * 修改状态
     * @param $shop
     * @param $status
     * @return array|\Exception
     * @throws \Exception
     */
    static function Status($shop, $status)
    {
        DB::beginTransaction();

        //修改店铺状态
        $shop->status = $status;
        if (!$shop->save()) {
            DB::rollBack();

            return error('失败');
        }

        //发送推送消息
        if ($status === self::STATUS_REFUSE) {
            $content = "您的{$shop->store_name}资料审核未通过，请重新提交审核资料。";
        } else {
            $content = "您的{$shop->store_name}资料审核通过，可以添加医生了";
        }
        $message = JpushShMessage::SendJpush($shop->id, JpushShMessage::TYPE_SYSTEM, $content, JpushShMessage::RECEIVE_SH);
        if ($message['status'] !== 1) {
            DB::rollBack();

            return $message;
        }
        DB::commit();

        return success('成功');
    }

    /**
     * 修改商户的VIP信息
     * @param $shop
     * @param $request
     * @param $huati_id
     * @return array
     */
    static function ShopVipModify($shop, $request, $huati_id)
    {
        DB::beginTransaction();
        foreach (['doclimit', 'goods_umber', 'consulttype', 'vip', 'vipendtime', 'store_title', 'lng', 'lat', 'url', 'city'] as $item) {
            $shop->$item = $request->$item;
        }
        $shop->is_hot = $request->hot;
        $shop->pin_pic = ShanghuType::where('store_type', $request->store_type)->value('pin_pic');

        $shop->huati_id = $huati_id;
        $is_push = false;
        if (intval($request->vip) !== intval($shop->vip)) {
            $is_push = true;
        }
        //权限
        if (intval($request->vip) === 0) {
            $config = Store::select('title', 'docnum', 'shownum', 'consulttype')->first();
            $shop->doclimit = $config->docnum;
            $shop->goods_umber = $config->shownum;
            $shop->consulttype = $config->consulttype;
            $shop->vip = 0;
            $vip = $config->title;
            $is_push = false;
        } else {
            $config = Vip::select('title', 'docnum', 'shownum', 'consulttype')->find($request->vip);
            $shop->doclimit = $config->docnum;
            $shop->goods_umber = $config->shownum;
            $shop->consulttype = $config->consulttype;
            $shop->vip = $request->vip;
            $vip = $config->title;
        }

        try {
            if (!$shop->save()) {
                DB::rollBack();

                return error('保存失败');
            }
        } catch (Exception $exception) {
            logger($shop->id . '修改失败');
            DB::rollBack();

            return error('保存失败');
        }

        //添加phone
        $phones = explode(' ',$request->phone);
        //删掉以前的电话
        DB::table('s_shanghu_phone')->where('shanghu_id', $shop->id)->delete();
        //添加
        $phones_insert = [];
        foreach ($phones as $phone) {
            $phones_insert[] = [
                'shanghu_id' => $shop->id,
                'phone_num' => $phone
            ];
        }
        $phone_update = DB::table('s_shanghu_phone')->insert($phones_insert);
        if (!$phone_update) {
            DB::rollBack();

            return ['status' => 2, 'message' => '失败'];
        }

        if ($is_push) {
            //发送消息
            $message = JpushShMessage::SendJpush($shop->id, JpushShMessage::TYPE_SYSTEM, "您的vip{$vip}，到期时间" . date('Y-m-d H:i', $request->vipendtime), JpushShMessage::RECEIVE_SH);
            if ($message['status'] !== 1) {
                DB::rollBack();

                return $message;
            }
        }

        DB::commit();

        return success('成功');
    }

    /**
     * 拒绝新信息修改
     * @param $shop
     * @return array
     * @throws \Exception
     */
    static function NewInfoOff($shop)
    {
        $time = time();
        DB::beginTransaction();

        $shop->status = ShopInfo::STATUS_YES;
        $shop->checktime = $time;
        if (!$shop->save()) {
            DB::rollBack();

            return error('修改失败');
        }

        if (!ShopInfos::where('id', $shop->shinfoid)->update([
            'status' => ShopInfo::STATUS_REFUSE,
            'checktime' => $time,
        ])) {
            DB::rollBack();

            return error('修改失败');
        }

        //发送消息
        $message = JpushShMessage::SendJpush($shop->id, JpushShMessage::TYPE_SYSTEM, "尊敬的用户您好！您的{$shop->store_name}商家信息审核未通过，请重新修改。", JpushShMessage::RECEIVE_SH);
        if ($message['status'] !== 1) {
            DB::rollBack();

            return $message;
        }

        DB::commit();

        return success('成功');
    }

    /**
     * 同意新信息修改
     * @param $shop
     * @return array
     * @throws \Exception
     */
    static function NewInfoOn($shop)
    {
        $time = time();
        DB::beginTransaction();

        //修改商户信息
        $info = ShopInfos::find($shop->shinfoid);
        $shop->status = ShopInfo::STATUS_YES;
        $shop->phone = $info->phone;
        $shop->withdrawtype = $info->withdrawtype;
        $shop->alipay = $info->alipay;
        $shop->business_time1 = $info->business_time1;
        $shop->business_time2 = $info->business_time2;
        $shop->introduce = $info->introduce;
        $shop->checktime = $time;
        if (!$shop->save()) {
            DB::rollBack();

            return error('修改失败');
        }

        //修改审核信息状态
        $info->status = ShopInfo::STATUS_YES;
        $info->checktime = $time;
        if (!$info->save()) {
            DB::rollBack();

            return error('修改失败');
        }

        //修改图片
        ShanghuPic::where('shanghu_id', $shop->id)->delete();
//        if (!ShanghuPic::where('shanghu_id', $shop->id)->delete()) {
//            DB::rollBack();
//
//            return error('图片修改失败');
//        }
        $photos = [];
        $pics = json_decode($info->piclist);
        foreach ($pics as $key => $pic) {
            if ($key === 0) {
                $cover = ShanghuPic::COVER_ON;
            } else {
                $cover = ShanghuPic::COVER_OFF;
            }
            $photos[] = [
                'shanghu_id' => $shop->id,
                'pic' => $pic,
                'cover' => $cover
            ];
        }

        if (!ShanghuPic::insert($photos)) {
            DB::rollBack();

            return error('图片修改失败');
        }

        //发送消息
        $message = JpushShMessage::SendJpush($shop->id, JpushShMessage::TYPE_SYSTEM, "您的{$shop->store_name}商家信息审核通过。", JpushShMessage::RECEIVE_SH);
        if ($message['status'] !== 1) {
            DB::rollBack();

            return $message;
        }

        DB::commit();

        return success('成功');
    }
}
